package basic.courseLearn10.problem;

import org.junit.Test;

import java.util.HashMap;

//设计结构，完成以下三个方法，利用哈希表实现随机池
//1. insert(int num)：向随机池中插入一个数
//2. getRandom()：从随机池中随机取出一个数
//3. delete(int num)：从随机池中删除一个数
public class RandomPool {

    int size=0; //随机池的大小
    HashMap<Integer, Integer> poolA; //随机池A的哈希表
    HashMap<Integer, Integer> poolB; //随机池B的哈希表

    public void init(){
        poolA=new HashMap<Integer, Integer>();
        poolB=new HashMap<Integer, Integer>();
        size=0;
    }

    //向随机池中插入一个数，做到不重复插入
    public void insert(int num){
        //1. A插入
        poolA.put(size, num);
        //2. B插入
        poolB.put(num, size);
        size++;
    }

    //从随机池中随机取出一个数
    public int getRandom(){
        //1. 随机取出A中的一个数
        int index= (int)(Math.random()*size);
        int num=poolA.get(index);
        return num;
    }

    //从随机池中删除一个数
    public void delete(int num){
        //1. 从poolA,poolB中获得num的索引
        int index=poolB.get(num);
        //2. 获得最后一个数的索引
        int lastIndex=size-1;
        //3. 更新index的value
        poolA.put(index, poolA.get(lastIndex));
        poolB.remove(num);
        poolB.put(poolA.get(lastIndex), index);
        //4. 删除最后一个数
        poolA.remove(lastIndex);
        poolB.remove(poolA.get(lastIndex));
        size--;
    }

    //输出函数
    public void printPool(){
        System.out.print("PoolA:  ");

        poolA.forEach((k,v)->{
            System.out.print( k + ":" + v + " ");
        });
        System.out.println();
        System.out.print("PoolB:  ");
        poolB.forEach((k,v)->{
            System.out.print( k + ":" + v + " ");
        });
        System.out.println();
    }

    @Test
    public void test(){
        RandomPool pool=new RandomPool();
        pool.init();
        pool.insert(10);
        pool.insert(20);
        pool.insert(30);
        pool.printPool();
        System.out.println("Random number is "+pool.getRandom());
        pool.delete(20);
        pool.printPool();
    }




}
